package com.hc.controller;

import com.hc.common.bean.Result;
import com.hc.common.bean.ResultUtil;
import com.hc.domain.Role;
import com.hc.domain.User;
import com.hc.query.RoleCondition;
import com.hc.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.Null;
import java.io.Serializable;
import java.util.List;

/**
 * @author 舞遍邓城一条街
 * @description
 * @Date 2021/12/4 14:15
 */
@Slf4j
@RestController
@RequestMapping("/role")
public class RoleController {

    @Resource
    private RoleService roleService;

    @PostMapping
    public Result<Null> create(@RequestBody Role role) {
        boolean res = roleService.save(role);
        return res ? ResultUtil.success("添加成功") : ResultUtil.fail("添加失败");
    }


    @PutMapping
    public Result<Null> updateById(@RequestBody Role role) {
        boolean res = roleService.updateById(role);
        return res ? ResultUtil.success("更新成功") : ResultUtil.fail("更新失败");
    }

    @DeleteMapping("{id}")
    public Result<Null> removeById(@PathVariable Serializable[] id) {
        boolean res = false;
        // 批量删除,把状态改为2不可用
        for (Serializable serializable : id) {
            Role role = roleService.getById(serializable);
            if (role.getStatus()==1){
                role.setStatus(2);
                res = roleService.updateById(role);
            }else {
                return ResultUtil.fail("删除失败");
            }
        }
        return res ? ResultUtil.success("删除成功") : ResultUtil.fail("删除失败");
    }

    @GetMapping("{id}")
    public Result<Role> getById(@PathVariable Serializable id) {
        Role res = roleService.getById(id);
        return ResultUtil.<Role>success("查询成功").setData(res);
    }

    @GetMapping
    public Result<List<Role>> getByCondition(@RequestBody RoleCondition condition) {
        List<Role> list = roleService.queryByCondition(condition);
        return ResultUtil.<List<Role>>success("查询成功").setData(list);
    }

}
